package com.wholesmart.common.security.authentication;

import java.io.IOException;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wholesmart.common.utils.HttpSessionUtils;
import com.wholesmart.service.UserService;

/**
 * Spring Security 鉴权成功后的处理器
 * <p>
 * 当对用户进行登录授权时，如果授权成功就会交由该类处理。
 * <p>
 * 主要用于接收鉴权信息，然后自定义返回前端的Json消息，当然你也可以在这里根据需求做页面跳转。
 * <p>
 * 需要手动配置到WebSecurityConfigurerAdapter的实现内中。
 * 
 * @author dyw
 * @date 2019年10月11日
 */
@Component("wholesmartAuthenticationSuccessHandler")
public class WholesmartAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	/** Spring框架初始化后，这个类会被加载到IOC容器中，所以这里可以直接注入 */
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private UserService userService;
	private HttpSessionUtils sessionUtils = new HttpSessionUtils();

	/*
	 * Authentication对象封装了我们的认证信息
	 * 
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登陆成功");
		Object principal = authentication.getPrincipal();
		if (principal instanceof UserDetails) {
			String username = ((UserDetails) principal).getUsername();
			Set<String> map = userService.getFrontRoutesByUsername(username);
			sessionUtils.setAttribute(new ServletWebRequest(request), HttpSessionUtils.CURRENT_USER_KEY,
					username);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(map));
		}
	}
}
